package com.szosen.device.Xuezhi;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.szosen.application.MyApplication;
import com.szosen.bluetooth.BluetoothListActivity;
import com.szosen.device.jianhuyi.StringUtils;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.jkzj.util.Contants;
import com.szosen.util.BackGroundThread;
import com.szosen.util.BackGroundThread.BackGroundTask;
import com.szosen.util.Cache;
import com.szosen.util.TimeHelper;
import com.szosen.util.ToastTool;


public class XuezhiActivityBACK extends BaseActivity {
	private BluetoothAdapter mBluetoothAdapter;
	private BluetoothGattCharacteristic mNotifyCharacteristic;
	private BluetoothDevice mDevice;
	private String mDeviceAddress;
	private BluetoothLeService mBluetoothLeService;
	private static final int REQUEST_ENABLE_BT = 1;
	private static final long SCAN_PERIOD = 1000;
	TextView connect_status;
	EditText cholEditText;
	EditText trigEditText;
	EditText hdlEditText;
	EditText ldlEditText;
	Button bo_stable_button;
	Button find_device;
	Button upload_button;
	Context context;
	Activity act;
	ImageView temp_image;
	int tag = 0;
	int tag1 = 0;
	// Cache cache;
	public static final int UPLOAD_RESULT = 0x10040;
	public static final int OFFLINE_ERROR = 0x10043;
	public static final int OFFLINE_OK = 0x10042;
	public static final int OFFLINE_RESULT = 0x10041;
	public static final int OFFLINE_RESULT_OK = 0x10044;
	public static final int OFFLINE_RESULT_ERROR = 0x10047;
	String mTime = "";
	String yibangding = "已绑定";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_xuezhi);
		super.setTitleContent("【血脂测量】");
		mTime = TimeHelper.getCurrentTime();
		context = this;
		act = this;
		temp_image = (ImageView) findViewById(R.id.temp_image);
		connect_status = (TextView) findViewById(R.id.connect_status);
		bo_stable_button = (Button) findViewById(R.id.bo_stable_button);
		find_device = (Button) findViewById(R.id.find_device);
		upload_button = (Button) findViewById(R.id.upload_button);
		cholEditText = (EditText) findViewById(R.id.xuezhi_chol);
		trigEditText = (EditText) findViewById(R.id.xuezhi_trig);
		hdlEditText = (EditText) findViewById(R.id.xuezhi_hdl);
		ldlEditText = (EditText) findViewById(R.id.xuezhi_ldl);
		// bo_stable_button.setVisibility(View.INVISIBLE);
		// 为了方便用户操作。将上传和重新连接两个按钮调换了
		upload_button.setText("重新连接");
		upload_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String defaultAddress = MyApplication.getCache()
						.getDeviceAddress(Cache.XUEZHI);
				changeBT(defaultAddress);
			}
		});
		bo_stable_button.setText("上传数据");
		bo_stable_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				try {
					upload();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		find_device.setText("绑定设备");
		find_device.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 选择低功耗蓝牙的名称，然后记录。
				scanLeDevice();
				showDialog();
			}
		});
		if (!getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_BLUETOOTH_LE)) {
			Toast.makeText(this, "不支持低功率蓝牙", Toast.LENGTH_SHORT).show();
			finish();
		}
		final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();
		if (mBluetoothAdapter == null) {
			Toast.makeText(this, "不支持普通蓝牙", Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
//		 connect();
		// 直接开启连接。
		String defaultAddress = MyApplication.getCache().getDeviceAddress(
				Cache.XUEZHI);
		if (TextUtils.isEmpty(defaultAddress)) {
			connect_status
					.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECT_NOBOND);
			connect_status.setTextColor(Color.RED);
		} else {
			changeBT(defaultAddress);
		}

	}

	private void connect() {
		scanLeDevice();
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				Toast.makeText(context, "提交成功", 0).show();

				break;
			case -1:
			case -2:
				Toast.makeText(context, msg + "", 0).show();
				break;
			}

		}

	};
	private String btMac = "123456";
	private String btName = "tiwen";
	private String TAG = "TiwenActivity";

	private void upload() throws Exception {

		// String tempValue = temp.getText().toString();
		// if (tempValue.length() > 0) {// 体温有数据
		// tiwen uploadBean = new tiwen();
		// uploadBean.setIdCard(BaseActivity.getIdCard());
		// uploadBean.setTime(mTime);
		// uploadBean.setTemp(tempValue);
		// boolean b = DBService.add(uploadBean);
		// if (b) {
		// ToastTool.showLong(context, "数据保存成功");
		// } else {
		// ToastTool.showLong(context, "数据保存失败");
		// }
		// }
	}

	/***
	 * 启用后台线程上传数据
	 * 
	 * @param data
	 * @param path
	 */
	private void uploadInBack(final JSONObject data, final String path,
			final ContentValues values) {
		new BackGroundThread(new BackGroundTask() {

			@Override
			public void process() {
			}
		}).start();
	}

	/***
	 * 上传数据,data域由具体项目指定
	 * 
	 * @param data
	 * @param path
	 * @throws JSONException
	 */
	public void upload(JSONObject data, String path, ContentValues values) {
	}

	private void scanLeDevice() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				mBluetoothAdapter.stopLeScan(mLeScanCallback);
				if (tag1 == 1) {
					mHandler.removeCallbacks(this);
					System.out.println("清除执行");
					return;
				}
				if (mDevice == null) {
					mBluetoothAdapter.startLeScan(mLeScanCallback);
					System.out.println("重试");
				}
				mHandler.postDelayed(this, 3000);
				System.out.println("3秒后执行一次！");
			}
		}, SCAN_PERIOD);
	}

	ArrayList<String[]> deviceMacList = new ArrayList<String[]>();
	// Device scan callback.
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					System.out.println("到底的辅导费单反都辅导费：" + device.getName());
					// 扫描体温枪设备
					if (device.getName() != null
							&& device.getName().contains("ardio")) {
						String defaultAddress = MyApplication.getCache()
								.getDeviceAddress(Cache.XUEZHI);
						if (!TextUtils.isEmpty(defaultAddress)
								&& defaultAddress.equals(device.getAddress())) {
							addData(device.getName() + "(" + yibangding + ")",
									device.getAddress());
							// System.out.println("名字" + device.getName());
							mDevice = device;
							mDeviceAddress = device.getAddress();
							// System.out.println("获取设备mac地址" + mDeviceAddress);
							// registerReceiver(mGattUpdateReceiver,
							// makeGattUpdateIntentFilter());
							tag = 1;
							// Intent gattServiceIntent = new Intent(
							// TiwenActivity.this,
							// BluetoothLeService.class);
							// bindService(gattServiceIntent,
							// mServiceConnection,
							// BIND_AUTO_CREATE);
						} else {
							addData(device.getName(), device.getAddress());
						}
						// 如果第一次使用，没绑定过设备。
						if (TextUtils.isEmpty(defaultAddress)) {
							// 这里需要增加一个蓝牙的列表。然后点击后就得到这个设备，然后连接。
						}
					}
				}
			});
		}
	};

	private void addData(String name, String mac) {

		boolean isHas = false;
		for (int i = 0; i < deviceMacList.size(); i++) {
			String[] item = deviceMacList.get(i);
			String m = item[1];
			if (m.equals(mac)) {
				isHas = true;
			}
		}
		if (!isHas) {
			deviceMacList.add(new String[] { name, mac });
		}
		// 通知更新listView
		if (mMyAdapter != null) {
			mMyAdapter.notifyDataSetChanged();
		}
	}

	private void clearAllList() {
		if (deviceMacList != null) {
			deviceMacList.clear();
		}
	}

	class MyAdapter extends BaseAdapter {
		private ArrayList<String[]> mList = new ArrayList<String[]>();

		MyAdapter(ArrayList<String[]> list) {
			mList = list;
		}

		public void addData(String name, String mac) {
			boolean isHas = false;
			for (int i = 0; i < mList.size(); i++) {
				String[] item = mList.get(i);
				String m = item[1];
				if (m.equals(mac)) {
					isHas = true;
				}
			}
			if (!isHas) {
				mList.add(new String[] { name, mac });
			}
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public String[] getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder;
			// 只有为空时才构造
			if (convertView == null) {
				holder = new Holder();
				LayoutInflater inflater = LayoutInflater.from(context);
				convertView = inflater.inflate(
						R.layout.tiwen_listview_item_layout, null);
				holder.tv_name = (TextView) convertView
						.findViewById(R.id.tiwen_listview_item_tv_name);
				holder.tv_mac = (TextView) convertView
						.findViewById(R.id.tiwen_listview_item_tv_mac);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			String[] s = mList.get(position);
			holder.tv_name.setText(s[0]);
			holder.tv_mac.setText(s[1]);
			return convertView;
		}

		class Holder {
			TextView tv_name;// 蓝牙名字
			TextView tv_mac;// mac地址
		}

	}

	private AlertDialog mDeviceDialog = null;
	String this_bt_name = "", this_bt_mac = "";

	private void showDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				XuezhiActivityBACK.this);
		LayoutInflater inflater = (LayoutInflater) XuezhiActivityBACK.this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout tl = (LinearLayout) inflater.inflate(
				R.layout.activity_tiwen_dialog_chancedevice, null);
		final ListView lv_btdevice_lists = (ListView) tl
				.findViewById(R.id.lv_btdevice_lists);
		final LinearLayout ll_password = (LinearLayout) tl
				.findViewById(R.id.ll_tiwen_password);
		final EditText et_password = (EditText) ll_password
				.findViewById(R.id.et_tiwen_password);
		mMyAdapter = new MyAdapter(deviceMacList);
		lv_btdevice_lists.setAdapter(mMyAdapter);

		lv_btdevice_lists.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 点击一个蓝牙设备，就设定连接这个设备
				// 设置显示修改设备
				// 先把已经连接的取消。再连接新的。
				String[] item = (String[]) parent.getAdapter()
						.getItem(position);
				System.out.println("蓝牙名称：" + item[0] + ",蓝牙mac地址：" + item[1]);
				this_bt_name = item[0];
				this_bt_mac = item[1];
				if (!item[0].contains(yibangding)) {
					ll_password.setVisibility(View.VISIBLE);
				} else {
					changeBT(this_bt_mac);
				}

			}
		});
		builder.setView(tl);
		builder.setTitle("请选择蓝牙设备：");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (ll_password.getVisibility() != View.VISIBLE) {
					return;
				}
				String password = et_password.getText().toString();
				if (!TextUtils.isEmpty(password)
						&& password
								.equals(BluetoothListActivity.changeDevicePassword)) {
					// 把蓝牙设备列表清除。重新找设备。
					clearAllList();
					cholEditText.setText("");
					trigEditText.setText("");
					hdlEditText.setText("");
					ldlEditText.setText("");
					changeBT(this_bt_mac);
				} else {
					ToastTool.showShort(context, "密码不正确！");
				}
			}

		});
		builder.setNegativeButton("取消", null);
		mDeviceDialog = builder.create();
		mDeviceDialog.show();
	}

	private void changeBT(String address) {
		mDevice = null;
		try {
			unregisterReceiver(mGattUpdateReceiver);
			// isStopService = true;
			unbindService(mServiceConnection);
		} catch (Exception e) {
			e.printStackTrace();
		}
		connect_status
				.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING);
		connect_status.setTextColor(Color.BLUE);
		mDeviceAddress = address;
		// mDeviceAddress = device.getAddress();
		System.out.println("设定蓝牙的地址。" + address);
		MyApplication.getCache()
				.saveDeviceAddress(Cache.XUEZHI, mDeviceAddress);
		registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
		tag = 1;
		Intent gattServiceIntent = new Intent(XuezhiActivityBACK.this,
				BluetoothLeService.class);
		bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
		// clearAllList();
		if (mDeviceDialog != null && mDeviceDialog.isShowing()) {
			mDeviceDialog.dismiss();
		}
	}

	private final ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName componentName,
				IBinder service) {
			mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
					.getService();
			System.out.println("获取服务" + mBluetoothLeService);
			if (!mBluetoothLeService.initialize()) {
				finish();
			}
			boolean b = mBluetoothLeService.connect(mDeviceAddress);
			MyApplication.getCache().saveDeviceAddress(Cache.XUEZHI,
					mDeviceAddress);
			if (b) {
				System.out.println("连接成功");
			} else {
				System.out.println("连接失败");
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName componentName) {
			mBluetoothLeService = null;
		}
	};
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context1, Intent intent) {
			final String action = intent.getAction();
			if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {

			} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
					.equals(action)) {
				mDevice = null;
				connect_status
						.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
				connect_status.setTextColor(Color.RED);
				isStopService = true;
				// unregisterReceiver(mGattUpdateReceiver);
				// unbindService(mServiceConnection);
				// System.out.println("连接失败" + mDevice);
				// scanLeDevice();
				// 发现设备成功，连接成功
			} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
					.equals(action)) {
				connect_status
						.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS);
				connect_status.setTextColor(Color.BLUE);
				// cache.saveDeviceAddress("tiwen", mDeviceAddress);
				displayGattServices(mBluetoothLeService
						.getSupportedGattServices());
				sb_xuezhidata = new StringBuilder();
			} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
				try {
					String data = intent
							.getStringExtra(BluetoothLeService.TEMPEXTRA_DATA);
					System.out.println("ACTION_DATA_AVAILABLE低功耗蓝牙的数据：" + data);
					String ss = data.trim().replaceAll(" ", "")
							.replace("00", "");
					System.out.println("血脂有用的数据ss：" + ss);
					byte[] xuezhiBytes = StringUtils.HexToByteArr(ss);
					String xuezhiStr = new String(xuezhiBytes);
					// String xuezhiStr = new String(data.replace(" ",
					// "").replaceAll("00", ""));
					System.out.println("血脂有用的数据：" + xuezhiStr);
					Log.i(LOG_TAG, xuezhiStr);
					sb_xuezhidata.append(xuezhiStr);
					String data1 = data.replaceAll(" ", "").trim();
					if (sb_xuezhidata.toString().contains("TC/HDL")) {
						// 测量完成了。现在开始解析数据
						upload_button.setEnabled(true);
						parseXuezhiDatas(sb_xuezhidata.toString()
								.replace("\r\n", "").replace("\n", "").trim());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};

	//
	private void parseXuezhiDatas(String datas) {
		System.out.println("终极数据：" + datas);
	}

	private StringBuilder sb_xuezhidata = new StringBuilder();
	private final static String LOG_TAG = "xuezhi";

	private IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
		intentFilter
				.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
		return intentFilter;
	}

	private void displayGattServices(List<BluetoothGattService> gattServices) {
		if (gattServices == null)
			return;
		String uuid = null;
		for (BluetoothGattService gattService : gattServices) {
			System.out.println("gattService.getUuid().toString()uuid的列表。"
					+ gattService.getUuid().toString());
			if (gattService.getUuid().toString().contains("0000ffe0")) {
				System.out.println("//////////"
						+ gattService.getUuid().toString());
				List<BluetoothGattCharacteristic> gattCharacteristics = gattService
						.getCharacteristics();
				for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
					uuid = gattCharacteristic.getUuid().toString();
					System.out.println("获取的gattCharacteristic的Uuid" + uuid);
					if (uuid.contains("0000ffe4")) {
						int charaProp = gattCharacteristic.getProperties();
						if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
							if (mNotifyCharacteristic != null) {
								mBluetoothLeService
										.setCharacteristicNotification(
												mNotifyCharacteristic, false);
								mNotifyCharacteristic = null;
							}
							mBluetoothLeService
									.readCharacteristic(gattCharacteristic);
						}
						if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
							mNotifyCharacteristic = gattCharacteristic;
							mBluetoothLeService.setCharacteristicNotification(
									gattCharacteristic, true);
						}
					}
				}
			}
		}
	}

	boolean isStopService = false;
	private MyAdapter mMyAdapter;

	@Override
	protected void onDestroy() {
		tag1 = 1;
		if (mBluetoothLeService != null) {
			mBluetoothLeService.disconnect();
			mBluetoothLeService.close();
			if (!isStopService) {
				try {
					unbindService(mServiceConnection);
					unregisterReceiver(mGattUpdateReceiver);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		try {
			unregisterReceiver(mGattUpdateReceiver);
			isStopService = true;
			unbindService(mServiceConnection);
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		tag1 = 1;
		String connectStatus = connect_status.getText().toString();
		if (connectStatus
				.equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING)) {
			ToastTool.showLong(context, "正在连接设备，请勿退出!");
		} else {
			super.onBackPressed();
		}
	}

	private boolean isServiceRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if ("tiwenji.BluetoothLeService".equals(service.service
					.getClassName())) {
				System.out.println("服务正在运行");
				return true;
			}
		}
		return false;
	}
}